<template>
  <div class="p-4">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="performance-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <h4 class="section-title">基础信息</h4>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="成单日期" prop="pay_at">
              <el-date-picker
                v-model="form.pay_at"
                type="date"
                placeholder="选择成单日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="16">
      
          <el-col :span="12">
            <el-form-item label="客户邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          
          <el-col :span="12">
            <el-form-item label="业务员" prop="sales_id">
              <el-select v-model="form.sales_id" placeholder="请选择业务员" filterable>
                <el-option
                  v-for="item in salesOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原归属人" prop="original_own_id">
              <el-select v-model="form.original_own_id" placeholder="请选择原归属人" filterable clearable>
                <el-option
                  v-for="item in originalSalesOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="客户类型" prop="customer_type">
              <el-select v-model="form.customer_type" placeholder="请选择客户类型">
                <el-option
                  v-for="item in customerTypeOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户来源" prop="customer_source">
              <el-select v-model="form.customer_source" placeholder="请选择客户来源" style="width: 100%">
                <el-option
                  v-for="item in customerSourceOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="短信成单" prop="is_sms">
              <el-radio-group v-model="form.is_sms">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <!-- 支付信息 -->
      <div class="form-section">
        <h4 class="section-title">支付信息</h4>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="SA" prop="sa">
              <el-input v-model="form.sa" placeholder="请输入SA" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="原始金额" prop="original_order_fee">
              <el-input v-model="form.original_order_fee" placeholder="请输入（选填）" />
            </el-form-item>
          </el-col>
          <el-col :span="3">  
              <el-select v-model="form.original_currency" placeholder="请选择币种" filterable prop="original_currency">
                <el-option
                  v-for="item in currencyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-col>
        </el-row>
  
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="原订单金额" prop="order_fee">
              <el-input v-model="form.order_fee" placeholder="请输入（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="支付通道" prop="payment_channel">
              <el-select v-model="form.payment_channel" placeholder="请选择支付通道">
                <el-option
                  v-for="item in paymentChannelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账号" prop="ta">
              <el-input v-model="form.ta" placeholder="请输入收款账号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="流水号" prop="pr">
              <el-input v-model="form.pr" placeholder="请输入流水号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="到账状态" prop="payment_verified_status">
              <el-select v-model="form.payment_verified_status" placeholder="请选择到账状态">
                <el-option
                  v-for="item in paymentVerifiedStatusOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到账备注" prop="payment_verified_remark">
              <el-input v-model="form.payment_verified_remark" placeholder="请输入到账备注（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <!-- 备注信息 -->
      <div class="form-section">
        <h4 class="section-title">备注信息</h4>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="最低售价超额" prop="exceed_remark">
              <el-input v-model="form.exceed_remark" placeholder="请输入（选填）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="帮扶人" prop="help_remark">
              <el-input v-model="form.help_remark" placeholder="请输入帮扶人（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="SHOP" prop="shop">
              <el-input v-model="form.shop" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电联" prop="tel_connection_id">
              <el-select v-model="form.tel_connection_id" placeholder="请选择电联员工">
                <el-option
                  v-for="item in telConnectionOptions"
                  :key="item.id"
                  :label="item.nickname || item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="数据来源" prop="sources_remark">
              <el-input v-model="form.sources_remark" placeholder="请输入（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入（选填）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, PropType, onMounted, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";

interface SelectOption {
  label: string;
  value: number | string;
  name?: string;
}

interface TelConnectionOption {
  id: number;
  username: string;
  nickname?: string;
}

interface FormData {
  email?: string;
  phone?: string;
  sales_id?: number;
  original_own_id?: number;
  customer_type?: number;
  customer_source?: number;
  is_sms?: number;
  sa?: string;
  original_order_fee?: string;
  order_fee?: string;
  original_currency?: string;
  payment_channel?: string;
  ta?: string;
  pr?: string;
  exceed_remark?: string;
  help_remark?: string;
  shop?: string;
  tel_connection_id?: number;
  sources_remark?: string;
  remark?: string;
  pay_at?: string;
  payment_verified_status?: number;
  payment_verified_remark?: string;
}

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object as PropType<FormData>,
    default: () => ({})
  },
  salesOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  originalSalesOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  customerTypeOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  customerSourceOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  paymentChannelOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  currencyOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  paymentVerifiedStatusOptions: {
    type: Array as PropType<SelectOption[]>,
    default: () => []
  },
  telConnectionOptions: {
    type: Array as PropType<TelConnectionOption[]>,
    default: () => []
  },
  onSubmit: {
    type: Function as PropType<(data: FormData) => void>,
    default: undefined
  }
});

const emit = defineEmits<{
  submit: [data: FormData];
}>();

const formRef = ref<FormInstance>();

// 表单数据初始化
const initForm = (): FormData => ({
  email: '',
  phone: '',
  sales_id: undefined,
  original_own_id: undefined,
  customer_type: undefined,
  customer_source: undefined,
  is_sms: 0,
  sa: '',
  original_order_fee: '',
  order_fee: '',
  original_currency: '',
  payment_channel: '',
  ta: '',
  pr: '',
  exceed_remark: '',
  help_remark: '',
  shop: '',
  tel_connection_id: undefined,
  sources_remark: '',
  remark: '',
  pay_at: new Date().toISOString().split('T')[0], // 默认今天
  payment_verified_status: undefined,
  payment_verified_remark: '',
});

const form = reactive<FormData>(initForm());

// 监听salesOptions变化，设置默认业务员
watch(() => props.salesOptions, (newOptions) => {
  if (newOptions && newOptions.length > 0 && !props.isEdit && !form.sales_id) {
    form.sales_id = Number(newOptions[0].value);
  }
}, { immediate: true });

// 表单验证规则
const rules = reactive<FormRules<FormData>>({
  sales_id: [{ required: true, message: "请选择业务员", trigger: "change" }],
  customer_type: [{ required: true, message: "请选择客户类型", trigger: "change" }],
  customer_source: [{ required: true, message: "请选择客户来源", trigger: "change" }],
  sa: [{ required: true, message: "请输入SA金额", trigger: "blur" }],
  email: [
    {
      validator: (rule, value, callback) => {
        if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
          callback(new Error('请输入正确的邮箱格式'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 初始化表单数据
const initFormData = () => {
  if (props.isEdit && props.editData) {
    Object.keys(form).forEach(key => {
      if (props.editData[key] !== undefined) {
        form[key] = props.editData[key];
      }
    });
    
    // 处理原归属人：如果id为0，则设置为undefined（空选项）
    if (props.editData.original_own_id === 0) {
      form.original_own_id = undefined;
    }
    
    // 处理日期格式
    if (props.editData.pay_at) {
      // 如果是时间戳，转换为日期字符串
      const payAt = typeof props.editData.pay_at === 'number' 
        ? new Date(props.editData.pay_at * 1000).toISOString().split('T')[0]
        : props.editData.pay_at;
      form.pay_at = payAt;
    }
    
    // 修复customer_type：如果是字符串名称，转换为对应的value值
    if (form.customer_type && typeof (form.customer_type as any) === 'string') {
      const match = props.customerTypeOptions.find(item => item.name === (form.customer_type as any));
      if (match) {
        form.customer_type = Number(match.value);
      }
    }
    
    // 修复customer_source：如果是字符串名称，转换为对应的value值
    if (form.customer_source && typeof (form.customer_source as any) === 'string') {
      const match = props.customerSourceOptions.find(item => item.name === (form.customer_source as any));
      if (match) {
        form.customer_source = match.value as any;
      }
    }
  } else {
    // 新增模式，重置表单
    Object.assign(form, initForm());
    // 设置默认业务员
    if (props.salesOptions && props.salesOptions.length > 0) {
      form.sales_id = Number(props.salesOptions[0].value);
    }
  }
};

// 监听编辑数据变化
watch(() => [props.isEdit, props.editData], () => {
  initFormData();
}, { immediate: true, deep: true });

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    const formData = { ...form };
    emit('submit', formData);
    
    // 如果提供了onSubmit回调，也调用它
    if (props.onSubmit) {
      props.onSubmit(formData);
    }
    
    return true; // 返回成功状态
  } catch (error) {
    console.log('Validation failed:', error);
    return false; // 返回失败状态
  }
};

// 表单重置
const handleReset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  if (!props.isEdit) {
    Object.assign(form, initForm());
  }
};

// 暴露方法给父组件
defineExpose({
  validateForm: handleSubmit,
  resetForm: handleReset,
  getFormData: () => ({ ...form })
});
</script>

<style scoped>
.performance-form {
  max-height: 79vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #eaeaea;
  padding-bottom: 8px;
}

.el-form-item {
  margin-bottom: 8px;
}
</style>